const { staff_collection } = require('../config')
const { db } = require('../config')
const { command } = require('../config')
const _ = command;
const axios = require('axios');

// 获取腾讯地图API Key
const apiKey = 'P6PBZ-5CDLN-ASMFL-SG26N-OE5HT-Q7BOJ'; // 请替换为您的API Key

// 统计装维看管的镇或街道的数量
exports.main = async (event, context) => {
    const count = await db.collection(staff_collection).where({ status: _.neq('离职'), position: "全职装维" }).count();
    var page, pageSize = 10;
    var pageNum = Math.ceil(count.total / pageSize);
    for (page = 1; page < pageNum; page++) {
        const staffInfo = await db.collection(staff_collection).where({ status: _.neq('离职'), position: "全职装维" }).field({ name: true, obdLongLat: true }).skip(page * pageSize).limit(pageSize).get();
        console.log('第', page+1, '页');
        for (staff of staffInfo.data) {
            console.log(staff.name, staff._id);
            // console.log(staff.name, staffInfo.data.length,staff.obdLongLat)
            points = staff.obdLongLat;
            // const points = [
            //     { lat:21.90282061, lng: 110.8443196 },
            //     { lat: 21.90529122, lng: 110.8400168 },
            //     { lat: 21.90306745, lng: 110.8459102 },
            //     { lat: 21.9020683, lng: 110.8426209 },
            //     { lat: 21.90239459, lng: 110.8485729 },
            //     // 更多点...
            // ];
            try {
                const townOrStreeInfo = await getTownOrStrees(points);
                if (townOrStreeInfo) {
                    console.log(townOrStreeInfo.townOrStrees, townOrStreeInfo.townOrStreesCount, '镇/街道，数量')
                    const staffInfo = await db.collection(staff_collection).where({ _id: staff._id }).limit(1).update({
                        obdTown: [...townOrStreeInfo.townOrStrees],
                        obdTownCount: townOrStreeInfo.townOrStreesCount
                    })
                }else{
                    console.log('无负责obd')
                }
            } catch (error) {
                return { statusCode: 500, body: JSON.stringify({ error: error.message }) };
            }
        }
    }
};
async function getTownOrStrees(points) {
    const results = [];
    if (points.length == 0) {
        return false;
    }
    for (let i = 0; i < points.length; i++) {
        const point = points[i];

        // 添加延迟
        if (i > 0) {
            await delay(90); // 延迟1秒  99次/1000ms=10  5次/1000ms=200
        }

        const lat = point.lat;
        const lng = point.lng;
        const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=${apiKey}`;

        try {
            const response = await axios.get(url);
            if (response.data.status === 0) {
                // const district = response.data.result.address_component.district;
                var res = response.data.result;
                if (res && res.address_reference && res.address_reference.town && res.address_reference.town.hasOwnProperty('title')) {
                    var townOrStree = res.address_reference.town.title;
                    // console.log(33333, res.address_component.district,res.address_component.street,res.address_reference.town.title);
                    results.push(townOrStree);
                } else {
                    console.log(res, "接口返回结果无title")
                }
            } else {
                console.error(`Failed to get townOrStree for (${lat}, ${lng}):`, response.data.message);
                results.push(null);
            }
        } catch (error) {
            console.error(`Error fetching data for (${lat}, ${lng}):`, error);
            results.push(null);
        }
    }

    // 处理查询结果
    const townOrStrees = results.filter(townOrStree => townOrStree !== null);
    // console.log("镇或街区名称:", townOrStrees);
    var unique = countUniqueTownOrStrees(townOrStrees);
    return unique;
}
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
// 计算跨越的区划数量
function countUniqueTownOrStrees(townOrStrees) {
    const uniqueTownOrStrees = new Set(townOrStrees);
    console.log("跨越的镇或街区划数量:", uniqueTownOrStrees.size);
    return { townOrStrees: uniqueTownOrStrees, townOrStreesCount: uniqueTownOrStrees.size };
}